<template>
  <div id="heatmapChart" style="width: 500px; height: 500px;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { markRaw, watch } from 'vue'
import { ref, onMounted } from 'vue'

const props = defineProps({
  labels: {
    type: Array,
    required: true
  },
  attentions: {
    type: Array,
    required: true
  },
  filterMin: {
    type: Number,
    required: true
  },
});

const updateChartOnPropsChange = () => {
  updateChart(props.labels, props.attentions)
}

watch([()=>props.labels, ()=>props.attentions, ()=>props.filterMin], ()=>{
  updateChartOnPropsChange()
})

const convertData = (data) => {
  // 将二维点阵数据转化成heatmap的[[x, y, value]]形式
  let result = []
  for (let i = 0; i < data.length; i++) {
    for (let j = 0; j < data[i].length; j++) {
      if (data[i][j] >= props.filterMin) {
        result.push([j, i, data[i][j]])
      }
    }
  }
  // console.log('result', result)
  return result
}

const dataMax = (data) => {
  const arr = data.flat()
  return Math.max(...arr)
}

const chart = ref(null)

const initChart = () => {
  const dom = document.getElementById('heatmapChart')
  // console.log('dom', dom)
  chart.value = markRaw(echarts.init(dom));
}


const updateChart = (labels, data) => {
  const option = {
    title: {
      text: '自注意力热力图',
      left: 'center'
    },
    tooltip: {
      // formatter: '{c}',
      formatter: (params) => {
        // console.log('tooltip', labels, params)
        const tip = `${labels[params.value[1]]}->${labels[params.value[0]]}: ${params.value[2].toFixed(3)}`
        // '<>'被解释成了html tag，所以要转换
        return tip.replaceAll('<', '&lt;')
      }
    },
    xAxis: {
      type: 'category',
      data: labels,
      axisLabel: {
        rotate: 90,
      },
    },
    yAxis: {
      type: 'category',
      data: labels,
      inverse: true
    },
    visualMap: {
      min: 0,
      max: dataMax(data),
      precision: 2,
      calculable: true,
      orient: 'vertical',
      right: '0%',
      top: '10%',
      color: ['#FF0000', '#00BFFF'],
    },
    series: [
      {
        name: 'heatmap',
        type: 'heatmap',
        data: convertData(data)
      },
    ],
  };
  chart.value.setOption(option);
}

onMounted(() => {
  // console.log('attentions', props.attentions)
  initChart()
  updateChartOnPropsChange()
});
</script>